<template>
  <div class="city-weather-container">
    <Header />
    <div class="weather-card">
      <h2>城市天气查询</h2>
      <div class="search-section">
        <select v-model="selectedCity" class="city-select">
          <option value="">请选择城市</option>
          <option v-for="city in cityList" :key="city.adcode" :value="city">
            {{ city.name }}
          </option>
        </select>
        <button @click="searchWeather" class="search-btn">查询天气</button>
      </div>

      <div class="weather-result" v-if="currentWeather">
        <h3>{{ currentWeather.lives[0].city }} 实时天气</h3>
        <div class="weather-details">
          <p>更新时间: {{ currentWeather.lives[0].reporttime }}</p>
          <p>天气: {{ currentWeather.lives[0].weather }}</p>
          <p>温度: {{ currentWeather.lives[0].temperature }}°C</p>
          <p>湿度: {{ currentWeather.lives[0].humidity }}%</p>
          <p>风向: {{ currentWeather.lives[0].winddirection }} {{ currentWeather.lives[0].windpower }}级</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { getWeather } from '@/api/gmap';
  import type { City, WeatherResponseType } from '@/types/gmap';
  import Header from '@/components/Header.vue';

  const selectedCity = ref<City | null>(null);
  const currentWeather = ref<WeatherResponseType | null>(null);

  // 示例城市列表，可以根据需要扩展
  const cityList: City[] = [
    { adcode: '110000', name: '北京市' },
    { adcode: '310000', name: '上海市' },
    { adcode: '440100', name: '广州市' },
    { adcode: '440300', name: '深圳市' },
    { adcode: '320100', name: '南京市' },
    { adcode: '330100', name: '杭州市' },
  ];

  const searchWeather = async () => {
    if (!selectedCity.value) return;

    try {
      const weatherData = await getWeather(selectedCity.value.adcode);
      currentWeather.value = weatherData;
    } catch (error) {
      console.error('获取天气数据失败:', error);
    }
  };
</script>

<style lang="scss" scoped>
  .city-weather-container {
    width: 100%;
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    gap: 20px;
    overflow: hidden; /* 防止内容溢出导致滚动条 */
    box-sizing: border-box; /* 确保padding包含在宽度内 */
  }

  .weather-card {
    width: 100%;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex: 1;
    overflow: hidden;
    box-sizing: border-box;
  }

  .search-section {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .city-select {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .search-btn {
    padding: 8px 16px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background: #0056b3;
    }
  }

  .weather-details {
    p {
      margin: 8px 0;
      color: #188980;
    }
  }
</style>